<!-- <template> -->
<!-- <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="角色权限管理">
        页面数据为 Mock 示例数据，非真实数据。
      </n-card>
    </div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
      >
        <template #tableTitle>
          <n-button type="primary">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            添加角色
          </n-button>
        </template>

        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>

    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="editRoleTitle">
      <div class="py-3 menu-list">
        <n-tree
          block-line
          cascade
          checkable
          :virtual-scroll="true"
          :data="treeData"
          :expandedKeys="expandedKeys"
          :checked-keys="checkedKeys"
          style="max-height: 950px; overflow: hidden"
          @update:checked-keys="checkedTree"
          @update:expanded-keys="onExpandedKeys"
        />
      </div>
      <template #action>
        <n-space>
          <n-button type="info" ghost icon-placement="left" @click="packHandle">
            全部{{ expandedKeys.length ? '收起' : '展开' }}
          </n-button>

          <n-button type="info" ghost icon-placement="left" @click="checkedAllHandle">
            全部{{ checkedAll ? '取消' : '选择' }}
          </n-button>
          <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">提交</n-button>
        </n-space>
      </template>
    </n-modal>
  </div> -->
<!-- </template> -->
<template>
  <div>
    <h1 class="text-center text-lg">角色列表</h1>
    <div class="flex">
      <n-button class="!flex-1" type="success" @click="show = true">
        <n-icon size="18">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
            <path
              d="M368.5 240H272v-96.5c0-8.8-7.2-16-16-16s-16 7.2-16 16V240h-96.5c-8.8 0-16 7.2-16 16 0 4.4 1.8 8.4 4.7 11.3 2.9 2.9 6.9 4.7 11.3 4.7H240v96.5c0 4.4 1.8 8.4 4.7 11.3 2.9 2.9 6.9 4.7 11.3 4.7 8.8 0 16-7.2 16-16V272h96.5c8.8 0 16-7.2 16-16s-7.2-16-16-16z"
            />
          </svg>
        </n-icon>
        新增
      </n-button>
      <n-pagination
        v-model:page="a.page"
        :page-count="a.maxPage"
        class="text-center"
        :page-slot="5"
      />
      <n-auto-complete
        class="!flex-2"
        v-model:value="valueRef"
        :input-props="{
          autocomplete: 'disabled',
        }"
        :options="options"
        placeholder="请输入姓名"
        @keyup.enter="fuzzy()"
      />
      <n-button type="primary" @click="fuzzy()"> 搜索 </n-button>
    </div>
    <!-- 抽屉 -->
    <n-drawer v-model:show="show" :width="502">
      <n-drawer-content title="新增角色" closable>
        <NRadioGroup>
          <!-- 表单 -->
          <n-form ref="formRef" :label-width="200" :model="formValue" :rules="rules">
            <n-form-item label="姓名" path="user.name">
              <n-input v-model:value="formValue.name" placeholder="输入姓名" />
            </n-form-item>
            <n-form-item label="电话" path="phone">
              <n-input v-model:value="formValue.phone" placeholder="输入电话" />
            </n-form-item>
            <n-form-item label="地址" path="address">
              <n-input v-model:value="formValue.address" placeholder="输入地址" />
            </n-form-item>
            <n-form-item label="性别" path="sex">
              <n-select v-model:value="formValue.sex" :options="sexOption" placeholder="选择性别" />
            </n-form-item>
            <n-form-item label="状态" path="state">
              <n-select
                v-model:value="formValue.description"
                :options="stateOption"
                placeholder="选择状态"
              />
            </n-form-item>
            <n-form-item label="权限" path="role">
              <n-select
                v-model:value="formValue.duty"
                :options="roleOption"
                placeholder="选择权限"
              />
            </n-form-item>
            <n-form-item label="部门" path="department">
              <n-select
                v-model:value="formValue.org"
                :options="departmentOption"
                placeholder="选择部门"
              />
            </n-form-item>
          </n-form>
          <n-space vertical>
            <n-button type="success" @click="get(), (show = false)"> 确定 </n-button>
          </n-space>
        </NRadioGroup>
      </n-drawer-content>
    </n-drawer>

    <n-space vertical>
      <n-table striped>
        <thead>
          <tr>
            <th>姓名</th>
            <th>
              角色名称
              <QuerySelect
                v-model:value="a.conditions"
                class="!w-24"
                name="role"
                label="days"
                :options="roleOption"
              />
            </th>
            <th>
              状态
              <QuerySelect
                v-model:value="a.conditions"
                class="!w-24"
                name="state"
                label="days"
                :options="stateOption"
              />
            </th>
            <th>
              所属部门
              <QuerySelect
                v-model:value="a.conditions"
                class="!w-24"
                name="department"
                label="days"
                :options="departmentOption"
              />
            </th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="person in a.todos" :key="person.id">
            <td>{{ person.name }}</td>
            <td>{{ person.duty }}</td>
            <td>{{ person.description }}</td>
            <td>{{ person.org }}</td>
            <td>
              <n-popselect
                v-model:value="person.duty"
                :options="roleOption"
                @click="compile(person)"
                trigger="click"
              >
                <n-button type="info"> 编辑 </n-button>
              </n-popselect>
              <n-popconfirm
                @positive-click="handlePositiveClick(person.id)"
                @negative-click="handleNegativeClick"
              >
                <template #trigger>
                  <n-button type="warning">重置密码</n-button>
                </template>
                是否重置密码为123456
              </n-popconfirm>
            </td>
          </tr>
        </tbody>
      </n-table>
    </n-space>
  </div>
</template>
<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { FormInst, NButton, useMessage } from 'naive-ui';
  import { roleOption, stateOption, departmentOption, sexOption } from './constant';
  import { addPersons, addUser, putRole, getMohu, personName } from '@/api/system/role';
  import { putUser } from '@/api/system/user';
  import { usequanju } from '@/views/system/role/roleStore';
  import QuerySelect from './QuerySelect.vue';
  import { throttle } from 'lodash-es';

  const formRef = ref<FormInst | null>(null);

  let show = ref(false);
  const mima = ref(123456);
  const message = useMessage(),
    handlePositiveClick = async (x) => {
      const chong = await putUser(mima, x);
      message.info('已重置');
      console.log(chong);
    },
    handleNegativeClick = () => {
      message.info('未重置');
    };

  const valueRef = ref(''),
    options = ref<string[]>([]);

  const fuzzy = async () => {
    if (valueRef.value == '') return;
    options.value = [];
    const momu = await getMohu(valueRef.value);
    // console.log(momu);
    // a.todos = [];
    if (momu.length > 0) {
      momu.forEach(async (e) => {
        options.value.push(e.name);
      });
    }
    oor();
  };

  const oor = async () => {
    const name = await personName(valueRef.value);
    // console.log(name);
    if (name.length) {
      a.todos = name;
    }
  };

  // 监听
  watch(
    valueRef,
    throttle(() => {
      if (valueRef.value == '') {
        a.search();
      } else {
        fuzzy();
      }
    }, 500)
  );

  const a = usequanju();
  a.search();
  const formValue = reactive({
      name: '',
      sex: '男',
      phone: '',
      address: '',
      description: '正常',
      org: '人事',
      duty: '管理员',
    }),
    rules = {
      name: {
        required: true,
        message: '请输入姓名',
        trigger: 'blur',
      },
      phone: {
        required: true,
        message: '请输入电话',
        trigger: ['input', 'blur'],
      },
      address: {
        required: true,
        message: '请输入地址',
        trigger: ['input', 'blur'],
      },
    };
  // 查找
  // console.log(persons.value);
  const compile = async (item: any) => {
    const putRele = await putRole(item);
    return putRele;
  };
  // console.log(persons);

  // 增加
  const word = ref(123456);
  let val = formValue;
  let get = async () => {
    val = formValue;
    // 新增员工
    const data = await addPersons(val);
    // 新增用户
    const user = await addUser(data.phone, word.value, data.id);

    a.todos.unshift(data);
    return user;
  };

  // import { reactive, ref, unref, h, onMounted } from 'vue';
  // import { useMessage } from 'naive-ui';
  // import { BasicTable, TableAction } from '@/components/Table';
  // import { getRoleList } from '@/api/system/role';
  // import { getMenuList } from '@/api/system/menu';
  // import { columns } from './columns';
  // import { PlusOutlined } from '@vicons/antd';
  // import { getTreeAll } from '@/utils';
  // import { useRouter } from 'vue-router';

  // const router = useRouter();
  // const message = useMessage();
  // const actionRef = ref();

  // const showModal = ref(false);
  // const formBtnLoading = ref(false);
  // const checkedAll = ref(false);
  // const editRoleTitle = ref('');
  // const treeData = ref([]);
  // const expandedKeys = ref([]);
  // const checkedKeys = ref(['console', 'step-form']);

  // const params = reactive({
  //   pageSize: 5,
  //   name: 'xiaoMa',
  // });

  // const actionColumn = reactive({
  //   width: 250,
  //   title: '操作',
  //   key: 'action',
  //   fixed: 'right',
  //   render(record) {
  //     return h(TableAction, {
  //       style: 'button',
  //       actions: [
  //         {
  //           label: '菜单权限',
  //           onClick: handleMenuAuth.bind(null, record),
  //           // 根据业务控制是否显示 isShow 和 auth 是并且关系
  //           ifShow: () => {
  //             return true;
  //           },
  //           // 根据权限控制是否显示: 有权限，会显示，支持多个
  //           auth: ['basic_list'],
  //         },
  //         {
  //           label: '编辑',
  //           onClick: handleEdit.bind(null, record),
  //           ifShow: () => {
  //             return true;
  //           },
  //           auth: ['basic_list'],
  //         },
  //         {
  //           label: '删除',
  //           onClick: handleDelete.bind(null, record),
  //           // 根据业务控制是否显示 isShow 和 auth 是并且关系
  //           ifShow: () => {
  //             return true;
  //           },
  //           // 根据权限控制是否显示: 有权限，会显示，支持多个
  //           auth: ['basic_list'],
  //         },
  //       ],
  //     });
  //   },
  // });

  // const loadDataTable = async (res: any) => {
  //   let _params = {
  //     ...unref(params),
  //     ...res,
  //   };
  //   return await getRoleList(_params);
  // };

  // function onCheckedRow(rowKeys: any[]) {
  //   console.log(rowKeys);
  // }

  // function reloadTable() {
  //   actionRef.value.reload();
  // }

  // function confirmForm(e: any) {
  //   e.preventDefault();
  //   formBtnLoading.value = true;
  //   setTimeout(() => {
  //     showModal.value = false;
  //     message.success('提交成功');
  //     reloadTable();
  //     formBtnLoading.value = false;
  //   }, 200);
  // }

  // function handleEdit(record: Recordable) {
  //   console.log('点击了编辑', record);
  //   router.push({ name: 'basic-info', params: { id: record.id } });
  // }

  // function handleDelete(record: Recordable) {
  //   console.log('点击了删除', record);
  //   message.info('点击了删除');
  // }

  // function handleMenuAuth(record: Recordable) {
  //   editRoleTitle.value = `分配 ${record.name} 的菜单权限`;
  //   checkedKeys.value = record.menu_keys;
  //   showModal.value = true;
  // }

  // function checkedTree(keys) {
  //   checkedKeys.value = [checkedKeys.value, ...keys];
  // }

  // function onExpandedKeys(keys) {
  //   expandedKeys.value = keys;
  // }

  // function packHandle() {
  //   if (expandedKeys.value.length) {
  //     expandedKeys.value = [];
  //   } else {
  //     expandedKeys.value = treeData.value.map((item: any) => item.key) as [];
  //   }
  // }

  // function checkedAllHandle() {
  //   if (!checkedAll.value) {
  //     checkedKeys.value = getTreeAll(treeData.value);
  //     checkedAll.value = true;
  //   } else {
  //     checkedKeys.value = [];
  //     checkedAll.value = false;
  //   }
  // }

  // onMounted(async () => {
  //   const treeMenuList = await getMenuList();
  //   expandedKeys.value = treeMenuList.list.map((item) => item.key);
  //   treeData.value = treeMenuList.list;
  // });

  // function handleSuccess() {
  //   throw new Error('Function not implemented.');
  // }
</script>

<!-- <style lang="less" scoped></style> -->
